<?php

namespace App\Dao;

use App\Model\Anchor;
use App\Model\Online;
use App\Utils\MemcacheClient;
use Hyperf\Context\ApplicationContext;

class OnlineDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }

    public function insertData($uid)
    {
        $this->closeData($uid);
        $data = [
            'uid' => $uid,
            'date_time' => strtotime(date("Y-m-d")),
            'stime' => time(),
        ];
        Online::query()->insert($data);
    }

    public function closeData($uid)
    {
        $etime = time();
        $record = Online::query()->where('uid', $uid)->where('status', 0)->first();
        $record = modelToArray($record);
        if (!empty($record)) {
            $total = 0;
            if ($etime - $record['etime'] < 600 && $etime - $record['etime'] > 0) {
                $special_start_time = strtotime(date('Y-m-d', $record['stime']) . ' 01:00:00'); // 当天01:00的时间戳
                $special_end_time = strtotime(date('Y-m-d', $record['stime']) . ' 21:00:00'); // 当天21:00的时间戳
                // 计算特殊时长（21点后，1点前在线时长）
                if ($etime <= $special_start_time && $record['stime'] > ($special_end_time - 86400)) {
                    // 结束时间：在1点前，开始时间：在前一天21点后
                    $total = $etime - $record['stime'];
                } elseif ($etime <= $special_end_time && $record['stime'] < $special_start_time) {
                    // 结束时间：在21点前，开始时间：在1点前
                    $total = $special_start_time - $record['stime'];
                } elseif ($etime > $special_end_time && $record['stime'] < $special_start_time) {
                    // 结束时间：在21点后，开始时间：在1点前
                    $total = ($etime - $special_end_time) + ($special_start_time - $record['stime']);
                } elseif ($etime > $special_end_time && $record['stime'] < $special_end_time) {
                    // 结束时间：在21点后，开始时间：在21点前
                    $total = $etime - $special_end_time;
                } elseif ($etime > $special_end_time) {
                    // 结束时间：在21点后
                    $total = $etime - $record['stime'];
                }
            }

            Online::query()->where('id', $record['id'])->update(['etime' => $etime, 'status' => 1, 'total_time' => $etime - $record['stime'], 'special_total_time' => $total]);
        }
    }


}